# user/middleware.py
from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from rest_framework_simplejwt.tokens import UntypedToken
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from rest_framework_simplejwt.tokens import AccessToken  # ✅ 改这行
from django.contrib.auth.models import AnonymousUser
from user.models import SysUser
import jwt
from django.conf import settings

class JwtAuthenticationMiddleware(MiddlewareMixin):

    def process_request(self, request):
        white_list = [
            "/user/login",
            "/user/save",
            "/user/uploadImage",
            "/user/updateAvatar",
            "/user/search",
            "/user/action",  # ✅ 新加
            "/user/check",
            "/user/resetPassword",
            "/user/status",
            "/user/grantRole"

        ] # 注意：路径要和你 urls.py 的 login 路由一致
        path = request.path

        if path not in white_list and not path.startswith("/media"):
            print("🔐 进入 token 验证")
            raw_token = request.META.get('HTTP_AUTHORIZATION')
            print("🌐 接收到的 token:", raw_token)

            if not raw_token:
                return JsonResponse({"code": 401, "msg": "未提供 token"}, status=401)

            # ✅ 去掉 Bearer 前缀
            if raw_token.startswith("Bearer "):
                token = raw_token.split(" ")[1]
            else:
                token = raw_token

            try:
                print("🧪 开始验证 token:", token)
                AccessToken(token)  # ✅ 直接用这个
                print("✅ AccessToken 验证通过")

                payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
                print("✅ jwt.decode 解码成功，payload:", payload)
                user_id = payload.get("user_id")

                try:
                    user = SysUser.objects.get(id=user_id)
                    request.user = user  # 可在后续视图中使用 request.user
                except SysUser.DoesNotExist:
                    return JsonResponse({"code": 401, "msg": "用户不存在"}, status=401)

            except (InvalidToken, TokenError) as e:
                return JsonResponse({"code": 401, "msg": f"Token 无效: {str(e)}"}, status=401)
            except jwt.ExpiredSignatureError:
                return JsonResponse({"code": 401, "msg": "Token 已过期"}, status=401)
            except Exception as e:
                return JsonResponse({"code": 401, "msg": f"Token 验证失败: {str(e)}"}, status=401)

        else:
            print("✅ 白名单，跳过验证")
            return None
